package com.example.demo;

import org.docx4j.Docx4J;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.AltChunkType;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.P;

import java.io.*;
import java.util.List;

/**
 * 将读取到的html内容插入到word中
 */
public class Docx4jInsertHtml {

    static final String DIR_PATH = "/Users/wuxinbo/poiDemo/";
    static final String TEST_HTML="/Users/wuxinbo/poiDemo/ueditorDemo.html";
    static final String OUTPUT_DOCX_PATH = DIR_PATH + "mulu.docx";

    public static void main(String args[]) throws Exception {
        WordprocessingMLPackage mlPackage = WordprocessingMLPackage.load(new File(OUTPUT_DOCX_PATH));
        WordprocessingMLPackage mlPackage2 = (WordprocessingMLPackage) mlPackage.clone();
        MainDocumentPart mainDocumentPart = mlPackage.getMainDocumentPart();
        List<Object> contents = mainDocumentPart.getContent();
        MainDocumentPart documentPart = mlPackage2.getMainDocumentPart();
        List<Object> content2 = documentPart.getContent();
        content2.clear();
        for (Object o : contents) {
            content2.add(o);
            if (o instanceof P && o.toString().equals("占位符")) {
                BufferedReader reader = new BufferedReader(new FileReader(TEST_HTML));
                StringBuilder builder = new StringBuilder();
                reader.lines().forEach(str -> builder.append(str));
                documentPart.addAltChunk(AltChunkType.Html, builder.toString().getBytes());
            }
        }
        mlPackage2.save(new FileOutputStream(new File(DIR_PATH + "test.docx")), Docx4J.FLAG_EXPORT_PREFER_XSL);
    }

}
